import { Injectable } from '@angular/core';
import * as gc from 'src/app/global/const';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { JsonResult } from '../model/JsonResult';
import { UUID } from 'angular2-uuid';
import { map } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { NzSort, NzFilterOpts, NzFilterReference } from '../global/model';
import { TableStyle } from './table-style.service';
import { ArrayutilsService } from './arrayutils.service';

@Injectable({
  providedIn: 'root'
})
export class CashService {


  private sortData:NzSort = null;
  private path_pre = 'cash';
  filterOpts:{ [fieldName:string]:NzFilterOpts[] } = {};
  filterReference:NzFilterReference = new NzFilterReference();
  tableData:Cash[] = [];

  private url = {
    'deleteByPrimaryKey':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/deleteByPrimaryKey',
    'selectByPrimaryKey':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/selectByPrimaryKey',
    'selectAll':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/selectAll',
    'saveOne':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre,
    'insert':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/insert',
    'update':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/update',
  }
  constructor(
    private http:HttpClient,
    private datePipe:DatePipe,
    private arrUtils:ArrayutilsService
  ) { }

  deleteByPrimaryKey(iid:number):Observable<JsonResult>{
    const url = this.url.deleteByPrimaryKey + '/' + iid;
    return this.http.delete<JsonResult>(url);
  }

  selectByPrimaryKey(iid:number):Observable<JsonResult>{
    const url = this.url.selectByPrimaryKey + '/' + iid;
    return this.http.get<JsonResult>(url);
  }

  selectAll():Observable<JsonResult>{
    return this.http.get<JsonResult>(this.url.selectAll);
  }

  saveOne(record:Cash):Observable<JsonResult>{
    if( record === undefined || record === null ){
      let jr:JsonResult = new JsonResult();
      jr.code = 777;
      jr.msg = '数据为空，不可保存！';
      return of(jr);
    }
    record = this.transDate_push(record);
    console.log('即将要保存的对象是：');
    console.log(record);
    if( record.iid === undefined || record.iid === null || record.iid <=0 )
      return this.insert(record);
    else
      return this.update(record);
  }
  
  private insert(record:Cash):Observable<JsonResult>{
    return this.http.post<JsonResult>(this.url.insert,record).pipe(map((jr:JsonResult) =>{
      return this.transDate_pull(jr);
    }));
  }

  private update(record:Cash):Observable<JsonResult>{
    return this.http.put<JsonResult>(this.url.update,record).pipe(map((jr:JsonResult) =>{
      return this.transDate_pull(jr);
    }))
  }

  transDate_push(record:Cash):Cash{
    if( record === undefined || record === null ) return null;
    let bill_date:Date = new Date(record.bill_date);
    console.log('transDate_push');
    console.log(record);
    console.log('转换前bill_date:' + bill_date);
    if( bill_date !== undefined && bill_date !== null ){
      record.bill_date = this.datePipe.transform(bill_date,'yyyy-MM-dd HH:mm:ss');
    }

    return record;
  }

  transDate_pull(jr:JsonResult):JsonResult{
    if( jr === undefined || jr === null ) return null;
    if( jr.code !==1 )
      return jr;
    let data = jr.data;
    if( data === undefined || data === null )
      return jr;

    let bill_date:string = data.bill_date;
    let create_time:string = data.create_time;
    if( bill_date !== undefined && bill_date !== null && bill_date.length>0){
      data.bill_date = this.datePipe.transform(data.bill_date,"MM-dd");
    }

    if( create_time !== undefined && create_time !== null && create_time.length>0){
      data.create_time = this.datePipe.transform(data.create_time,"MM-dd HH:mm");
    }
    jr.data = data;
    return jr;
  }


  /**
   * 构建过滤用下拉数据源
   * @param td =tableData，表格数据，即本服务获取的业务数据数组
   * @param ts =tableStyle，本服务的业务数据对应表 talbe_style的数据
   */
  buildFilterOpts(td:Cash[],ts:TableStyle[]){

    for(let i=0;i<ts.length;i++){
      let ele = ts[i];
      let fieldName:string = ele.field_name;
      if( ele.filter === undefined || ele.filter === null || ele.filter.length<=0 || ele.filter ==='input'){
        console.log('字段' + fieldName + '无需构建下拉数据！');
        continue;
      }
        

      let arr:Cash[] = this.arrUtils.buildDistArray(td,[ele.field_name]);
      let filterOpts:NzFilterOpts[] = [];
      arr.forEach(e1 => {
        filterOpts.push({text:e1[fieldName],value:e1[fieldName]});
      });

      console.log('为字段' + fieldName + '构建的下拉数据是：');
      console.log(filterOpts);
      this.filterOpts[fieldName] = filterOpts;
    }
  }

  // 排序：调用 filter ，先过滤再排序
  sort(record:NzSort){
    this.sortData = record;
    this.filterGo();
  }

  filter(opts:string[],fieldName:string){
    console.log('过滤操作传入的两个参数是：');
    console.log(fieldName);
    console.log(opts);
    this.filterReference = new NzFilterReference();
    this.filterReference.fieldName = fieldName;
    this.filterReference.opts = opts;
    this.filterGo();
  }

  // 过滤：先过滤再排序
  filterGo(){
    // 过滤
    const displayData:Cash[] = this.tableData.filter(
      ( item:Cash ) =>{
        
        let fieldData:String = new String(item[this.filterReference.fieldName]);
        return this.filterReference.opts.some(
          ( val:string ) => fieldData.indexOf(val) !==-1
        ) ? true:false;

      }
    )

    this.tableData = displayData;

    // 无须排序
    if( this.sortData === undefined || this.sortData === null )
      return
    
      // 排序
    this.tableData = displayData.sort(
      (a,b) =>
      this.sortData.value === 'ascend'
      ? a[this.sortData.key!] > b[this.sortData.key!]
        ? 1
        : -1
      : b[this.sortData.key!] > a[this.sortData.key!]
      ? 1
      : -1
    );
    
  }
  
}


// Author：chanchaw
// Generator Version：1.0 - 2019年11月16日 16点46分
// This Model Created：Sat Feb 08 2020 21:41:41 GMT+0800 (中国标准时间)
// 记得导入UUID工具：import { UUID } from 'angular2-uuid';
export class Cash{
  iid:number;
  colpay:string;
  bill_date:string;
  company_sid:string;
  company_name:string;
  category:string;
  credit_amount:number;
  amount:number;
  amount_type:string;
  remark:string;
  operator:string;
  phpt:string;
  create_time:string;
  uuid:string;


  constructor(){
    this.uuid = UUID.UUID();
  }
}